import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import 'blue_logic.dart';

class BlueConnectPage extends StatelessWidget {
  const BlueConnectPage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(BlueLogic());

    return Scaffold(
      appBar: AppBar(
        title: const Text('蓝牙设置'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () => Get.back(),
        ),
        actions: [
          Obx(() => IconButton(
                icon: Icon(logic.isScanning.value ? Icons.stop : Icons.refresh),
                onPressed: () {
                  if (logic.isScanning.value) {
                    logic.stopScan();
                  } else {
                    logic.startScan();
                  }
                },
              )),
        ],
      ),
      body: Obx(() {
        return _buildScanList(logic);
      }),
    );
  }

  Widget _buildScanList(BlueLogic logic) {
    return ListView.builder(
      itemCount: logic.scanResults.length,
      itemBuilder: (context, index) {
        final result = logic.scanResults[index];
        return ListTile(
          title: Text(result.device.name.isEmpty ? '未知设备' : result.device.name),
          subtitle: Text(result.device.id.id),
          trailing: Text('${result.rssi} dBm'),
          onTap: () => logic.connectToDevice(result.device),
        );
      },
    );
  }

}
